options validvarname=upcase;
%let domain=adae;

/*************************************************************************************************/
*** get source data ;
%get_data(lst=ex);
%get_data(pre=sdtm,lib=sdtm,supp=y,lst=ae dm ex);
%get_data(pre=adam,lib=adam,lst=adsl);

*** gather info ;
 ** treatment and date from sdtm ex ;
proc sql noprint;
create table ex0 as select x.usubjid,subjid %vchk(sdtmex,excat,sql=y),
   visitnum,visit,extrt,exstdtc,exendtc as exendtco,rfpendtc
   from sdtmex as x
   left join sdtmdm as d on x.usubjid=d.usubjid order by subjid,exstdtc;
quit;
data ex1;
   set ex0;
   by subjid exstdtc;
   retain ord;
   if first.subjid then ord=1;
   else ord=ord+1;
run;
proc sql noprint;
create table ex as select a.*,coalescec(b.exstdtc,a.rfpendtc) as exendtc
   from ex1 as a left join ex1 as b on a.subjid=b.subjid and a.ord=b.ord-1;
 ** treatment from adsl ;
select distinct name into :trtp separated by " " from dictionary.columns
   where lowcase(libname)="work" and lowcase(memname)="adamadsl" and compress(name,,"dk")
   and compress(lowcase(name),,"d") in ("trtp"); %put ***(trtp=&trtp)***;
select distinct name into :trtpn separated by " " from dictionary.columns
   where lowcase(libname)="work" and lowcase(memname)="adamadsl" and compress(name,,"dk")
   and compress(lowcase(name),,"d") in ("trtpn"); %put ***(trtpn=&trtpn)***;
select distinct name into :trta separated by " " from dictionary.columns
   where lowcase(libname)="work" and lowcase(memname)="adamadsl" and compress(name,,"dk")
   and compress(lowcase(name),,"d") in ("trta"); %put ***(trta=&trta)***;
select distinct name into :trtan separated by " " from dictionary.columns
   where lowcase(libname)="work" and lowcase(memname)="adamadsl" and compress(name,,"dk")
   and compress(lowcase(name),,"d") in ("trtan"); %put ***(trtan=&trtan)***;
select distinct name into :trsdt separated by " " from dictionary.columns
   where lowcase(libname)="work" and lowcase(memname)="adamadsl" and compress(name,,"dk")
   and compress(lowcase(name),,"d") in ("trsdtm"); %put ***(trsdt=&trsdt)***;
quit;
%macro adsl_treatment(itm_lst,debug=0);
%let at_i=1;
%let merge=;
%let todel=;
%do %while(%scan(&itm_lst,&at_i,%str( ))^= );
   %let itm=%scan(&itm_lst,&at_i,%str( ));
   proc transpose data=adamadsl out=&itm.0(rename=(col1=&itm));
      var &&&itm;
      by usubjid;
   run;
   proc sql;
   create table &itm as select distinct usubjid,input(compress(_name_,,"dk"),best.) as ord,
      cats(upcase("trt"),compress(_name_,,"dk")) as id,&itm from &itm.0 order by usubjid,ord,id;
   quit;
   %let merge=&merge &itm;
   %let todel=&todel &itm.0 &itm;
   %let at_i=%eval(&at_i+1);
%end;
data adsl_trt0;
   %if %eval(&at_i-1)=1 %then %do; set &merge; %end;
   %else %do; merge &merge; %end;
   by usubjid ord id;
   if trsdt ne .;
   n+1;
run;
proc sql;
create table adsl_trt as select a.usubjid,a.id,a.trtp,a.trtpn,a.trta,a.trtan,a.trsdt,
   ifn(^missing(a.trsdt),coalesce(b.trsdt,datetime()),.) as tredt format=is8601dt.
   from adsl_trt0 as a left join adsl_trt0 as b on a.usubjid=b.usubjid and a.n=b.n-1;
quit;
/*%if ^&debug %then %do; %clrw(&todel adsl_trt0); %end;*/
%mend adsl_treatment;
%adsl_treatment(trtp trtpn trta trtan trsdt);
 ** assemble info ;
proc sql noprint;
select distinct varnum,name into :slnum separated by " ",:sltrt separated by ",sl."
   from dictionary.columns
   where lowcase(libname)="work" and lowcase(memname)="adamadsl" and compress(name,,"dk")
   and compress(lowcase(name),,"d") in ("trtp" "trtpn" "trta" "trtan" "trsdt" "tredt" "trsdtm" "tredtm")
   order by varnum; %put ***(sltrt=&sltrt)***;
create table info as select d.subjid,a.* /*aeterm,aestdtc*/
   %vchk(ex,excat,sql=y),ex.visitnum,ex.visit,ex.extrt,ex.exstdtc,ex.exendtc,d.rfstdtc,
   at.trtp,at.trtpn,at.trta,at.trtan,
   sl.siteid,sl.age,sl.sex,sl.race,sl.ethnic,/*sl.usubjid,*/sl.trtsdt,sl.trtedt,sl.trtsdtm,sl.trtedtm,
   sl.&sltrt,sl.reasexcl,sl.saffl
   from sdtmae as a left join ex on a.usubjid=ex.usubjid and exstdtc<=aestdtc<exendtc
   left join sdtmdm as d on a.usubjid=d.usubjid
   left join adsl_trt as at on a.usubjid=at.usubjid
   and %mk_dtc(dat=trsdt,wtim=1)<=aestdtc<%mk_dtc(dat=tredt,wtim=1)
   left join adamadsl as sl on a.usubjid=sl.usubjid
   order by a.usubjid,aestdtc,aeterm;
quit;

* Get the links from RELREC; 

data ae cm; 
set sdtm.relrec; 
if idvar = 'CMSPID' then output cm; 
else if idvar = 'AESPID' then output ae; 
run; 

proc sort data=cm; by usubjid relid; run ; 
proc sort data=ae; by usubjid relid; run ;

data cmae(drop=rdomain); 
merge cm(in=cm rename=(idvarval=cmspid))
      ae(in=ae rename=(idvarval=aespid)); 
by usubjid relid; 
run; 

*GET CMAENO for the listing; 

data cmae1; 
set cmae(where=(idvar='AESPID')); 
run; 

proc transpose data=cmae1 out=cmae2; 
var cmspid; 
by usubjid aespid; 
run; 

data cmae3; 
length cmno $10.; 
set cmae2; 
by usubjid aespid; 
cmno = catx(', ',col1,col2); 
run; 

proc sort data=info out=info_1; by usubjid aespid; run; 

data info_2; 
merge info_1(in=a) cmae3(in=b keep=usubjid aespid cmno); 
by usubjid aespid; 
if a; 
run;  


***; 

*** build adam ;
proc format;
   invalue inYN
   %upcase(
   "Y" = 1
   "N" = 0
);
   invalue inAESEV
   %upcase(
   "MILD" = 1
   "MODERATE"=2
/*   "SEVERE"=3*/
/*   "LIFE-THREATENING"=4*/
/*   "DEATH"=5*/
);
   invalue inASEV
   %upcase(
   "Mild" = 1
   "Moderate"=2
   "Severe"=3
/*   "Life-Threatening"=4*/
/*   "Death"=5*/
);   
   invalue inAEREL
   %upcase(
   "POSSIBLY RELATED"=3
   "UNRELATED"=1
   "UNLIKELY RELATED"=2
   "PROBABLY RELATED"=4
/*   "DEFINITELY RELATED"=5*/
);
   invalue inAEOUT
   %upcase(
	"RECOVERED/RESOLVED" = 1
   "NOT RECOVERED/NOT RESOLVED" = 2
   "RECOVERING/RESOLVING" = 3 
  
 );
   invalue inAETOX
   %upcase(
   " " = .
);   
   value faperiod
   1="Period 1"
   2="Period 2"
   0="Screening"
;
   picture __timdur (round)
      low - <0     ="0h 0m 0s"                                     (datatype=time)
      0 - <60      ="0h 0m"                                        (datatype=time)
      60 - <3600   ="%nrbquote(%)Hh %nrbquote(%)Mm"                (datatype=time)
      3600 - <86400="%nrbquote(%)Hh %nrbquote(%)Mm"                (datatype=time)
      86400 - high ="%nrbquote(%)nd %nrbquote(%)Hh %nrbquote(%)Mm" (datatype=time)
   ;                        
   picture __timddy (round)
      low - <0     ="0h 0m 0s"       (datatype=time)
      0 - <60      ="0h 0m"          (datatype=time)
      60 - <3600   ="%nrbquote(%)nd" (datatype=time)
      3600 - <86400="%nrbquote(%)nd" (datatype=time)
      86400 - high ="%nrbquote(%)nd" (datatype=time)
   ;                        
      /* 86400=number of seconds in one day */                                           
run;

data toflg;
   label
         ASTDT="Analysis Start Date"
         ASTTM="Analysis Start Time"
         ASTDTM="Analysis Start Date/Time"
         ASTDTF="Analysis Start Date Imputation Flag"
         ASTTMF="Analysis Start Time Imputation Flag"
         AENDT="Analysis End Date"
         AENTM="Analysis End Time"
         AENDTM="Analysis End Date/Time"
         AENDTF="Analysis End Date Imputation Flag"
         AENTMF="Analysis End Time Imputation Flag"
         ASTDY="Analysis Start Relative Day"
         AENDY="Analysis End Relative Day"
         ADURN="Analysis Duration (N)"
         ADURU="Analysis Duration Units"
         ADURC="Analysis Duration (C)"
         ADURFDC="Analysis Duration Since First Dose"
         ADURLDC="Analysis Duration Since Last Dose"
/*         APERIOD="Period"*/
/*         APERIODC="Period (C)"*/
/*         APHASE="Phase"*/
         TRTEMFL ="Treatment Emergent Analysis Flag" 
         PREFL ="Pre-treatment Flag"
         FUPFL ="Follow-up Flag"
         TRTP="Planned Treatment"
         TRTPN="Planned Treatment (N)"
         TRTA="Actual Treatment"
         TRTAN="Actual Treatment (N)"
         AESEVN="Severity/Intensity (N)"
         ASEV="Analysis Severity/Intensity"
         ASEVN="Analysis Severity/Intensity (N)"
         AERELN="Causality (N)"
         AREL="Analysis Causality"
         ARELN="Analysis Causality (N)"
         AETOXGRN="Standard Toxicity Grade (N)"
         ATOXGR="Analysis Toxicity Grade"
         ATOXGRN="Analysis Toxicity Grade (N)"
         TRTP="Planned Treatment"
         TRTPN="Planned Treatment (N)"
         TRTA="Actual Treatment"
         TRTAN="Actual Treatment (N)"
         /*
         AOUT="Analysis Outcome of Adverse Event"
         AOUTN="Analysis Outcome of Adverse Event (N)"
         AACN="Analysis Action Taken with Study Drug"
         AACNOTH="Analysis Other Action Taken"
         */
         SRCDOM="Source Data"
         SRCSEQ="Source Sequence Integer"
         AEENTPT="End Reference Time Point"
         AEWDAE="Subject withdrew due to AE"
         AEDISC="Leading To Discontinuation"
         AEACNOTH="Other Action Taken"
         CMNO = "Concomitant Medication Number" 
         AESDTH = "Results in Death";
   ;
   format astdt aendt date9. asttm aentm time5. astdtm aendtm datetime13.;
   length srcdom $2. /*aperiodc aphase*/ adurc adurfdc adurldc $40. asev arel atoxgr $90. aeentpt $30. 
          trtemfl prefl fupfl aewdae aedisc astdtf asttmf aendtf aentmf $1.;
   set info_2; 
   srcdom=domain;
   srcseq=aeseq;

   if aesev=" " then aesev=" ";
   aesevn = input(aesev, inasev.);
   asev=propcase(aesev);
   asevn = input(aesev, inasev.);
   aereln=input(aerel,inaerel.);
   arel=strip(propcase(aerel));
   areln=input(aerel,inaerel.);
   if areln<3 then relflg=areln;
   else relflg=3;
   if aetoxgr=" " then aetoxgr=" ";
   aetoxgrn=input(aetoxgr,inaetox.);
   atoxgr=strip(propcase(aetoxgr));
   atoxgrn=input(aetoxgr,inaetox.);
/*
   aout=propcase(aeout);
   aoutn=input(aeout,inaeout.);
   aacn=propcase(aeacn);
*/
   AEENTPT=upcase("FINAL VISIT");
   if aeacnoth=" " then aeacnoth=" ";
   aacnoth=propcase(aeacnoth);
   if index(lowcase(aeacnoth),"subject withdrawn")>0 then aewdae=upcase("y");
   else aewdae=upcase("n");

   *** date ;
/*   if .<visitnum then do; aperiodc=upcase("period 1"); aperiod=1; end;*/
/*   if missing(aphase) then aphase=" ";*/

   %adt(ae,id=st);
   %adt(ae,id=en);
   if missing(astdtf) then astdtf=" ";
   if missing(asttmf) then asttmf=" ";
   if missing(aendtf) then aendtf=" ";
   if missing(aentmf) then aentmf=" ";

   if n(trtsdtm,astdtm/*,trtedtm*/)=2 then do;
      if .<trtsdtm<=astdtm/*<=trtedtm*/ then trtemfl=upcase("y");
      else if .<astdtm<trtsdtm then trtemfl=upcase("n");
   end;
   else if n(trtsdt,astdt/*,trtedt*/)=2 then do;
      if .<trtsdt<=astdt/*<=trtedt*/ then trtemfl=upcase("y");
      else if .<astdt<trtsdt then trtemfl=upcase("n");
   end;
   *if missing(trtemfl) then trtemfl=aetrtem;

   if n(trtsdtm,astdtm)=2 and .<astdtm<trtsdtm then prefl=upcase("y");
   else if n(trtsdt,astdt)=2 and .<astdt<trtsdt then prefl=upcase("y");
   if n(astdtm,trtedtm)=2 and .<trtedtm<astdtm then fupfl=upcase("y");
   else if n(astdt,trtedt)=2 and .<trtedt<astdt then fupfl=upcase("y");

   *** automated time change ;
   dst_m_st=dhms(nwkdom(2,1,3,year(astdt)),01,59,59);
   dst_m_en=dhms(nwkdom(2,1,3,year(astdt)),02,00,00);
   dst_n_st=dhms(nwkdom(1,1,11,year(astdt)),01,00,00);
   dst_n_en=dhms(nwkdom(1,1,11,year(astdt)),02,00,00);

   *** duration ;

   if n(astdt,aendt)=2 then do;
      adurn=round(aendt-astdt,1)*86400;
      if .<astdt<=dst_n_st and dst_n_en<=aendt then do;
         adurn=adurn+3600;
         if lowcase(trtemfl)="y" then timechg=1;
      end;
      else if .<astdt<=dst_m_st and dst_m_en<=aendt then do;
         adurn=adurn-3600;
         if lowcase(trtemfl)="y" then timechg=2;
      end;
      adurc=strip(put(adurn,__timdur.));
      aduru=upcase("seconds");
   end;

   if n(astdtm,aendtm)=2 then do;
      adurn=round(aendtm-astdtm,1);
      if .<astdtm<=dst_n_st and dst_n_en<=aendtm then do;
         adurn=adurn+3600;
         if lowcase(trtemfl)="y" then timechg=1;
      end;
      else if .<astdtm<=dst_m_st and dst_m_en<=aendtm then do;
         adurn=adurn-3600;
         if lowcase(trtemfl)="y" then timechg=2;
      end;
      adurc=strip(put(adurn,__timdur.));
      aduru=upcase("seconds");
   end;

   

   *** time since last dose ;
   if ^missing(%rmtime(exstdtc)) then xstdt=input(%rmtime(exstdtc),is8601da.);
   if ^missing(%kptime(exstdtc)) then xsttm=input(%kptime(exstdtc),is8601tm.);
   if nmiss(xstdt,xsttm)=0 then xstdtm=input(%rmtime(exstdtc)||"%uc(t)"||%kptime(exstdtc),is8601dt.);
   if n(astdtm,xstdtm)=2 then do;
      adurldn=round(astdtm-xstdtm,1);
      if .<xstdtm<=dst_n_st and dst_n_en<=astdtm then do;
         adurldn=adurldn+3600;
         if lowcase(trtemfl)="y" then timechg=1;
      end;
      else if .<xstdtm<=dst_m_st and dst_m_en<=astdtm then do;
         adurldn0=adurldn;
         adurldn=adurldn-3600;
         if lowcase(trtemfl)="y" then timechg=2;
      end;
      adurldc=strip(put(adurldn,__timdur.));
   end;
   else if n(astdt,xstdtm)=2 then do;
      tmpdtm=input(%rmtime(aestdtc)||"%uc(t)23:59",is8601dt.);
      adurldn0=adurldn;
      adurldn=round(tmpdtm-xstdtm,1)+86400;
      adurldc=strip(put(adurldn,__timddy.));
   end;
 
   *** time since first dose ;
   if n(astdtm,tr01sdtm)=2 then do;
      adurfdn=round(astdtm-tr01sdtm,1);
      if .<tr01sdtm<=dst_n_st and dst_n_en<=astdtm then do;
         adurfdn=adurfdn+3600;
         *if lowcase(trtemfl)="y" then timechg=1;
      end;
      else if .<tr01sdtm<=dst_m_st and dst_m_en<=astdtm then do;
         adurfdn=adurfdn-3600;
         *if lowcase(trtemfl)="y" then timechg=2;
      end;
      adurfdc=strip(put(adurfdn,__timdur.));
   end;
   else if n(astdt,tr01sdtm)=2 then do;
      tmpdtm=input(%rmtime(aestdtc)||"%uc(t)23:59",is8601dt.);
      adurfdn=round(tmpdtm-tr01sdtm,1)+86400;
      adurfdc=strip(put(adurfdn,__timddy.));
   end;
/*
   if lowcase(aeacnoth)="withdrawn from study due to ae" or lowcase(aeacn)="drug withdrawn"
   then aedisc=propcase("yes");
   else aedisc=propcase("no");*/
   aedisc=propcase(strip(aedis));
   aesdth = ''; 
      if TRTEMFL="N" then TRTEMFL=" "; else TRTEMFL=strip(TRTEMFL);
run;

proc sql;
create table chk_tmchg as select usubjid,aeterm,ASTDTM,AENDTM,
   dst_n_st format=datetime23.,dst_n_en format=datetime23.,
   dst_m_st format=datetime23.,dst_m_en format=datetime23.,trtemfl,timechg
   from toflg;
create table chk_tmchg2 as select subjid,TRT01P,aeterm,trtemfl,/*aetrtem,*/aedisc,ASTDTM,
   TRTP,TR01SDTM,exstdtc,exendtc,adurc,adurfdc,adurldc,adurldn0,adurldn,timechg
   from toflg;
create table chk_trtem as select subjid,aeterm,aestdtc,rfstdtc,trtsdt,trtsdtm,astdt,astdtm,trtedt,trtedtm,/*aetrtem,*/trtemfl
   from toflg;
create table chk_out as select subjid,aeterm,aestdtc,aeendtc,aeout
   from toflg where missing(aeout) and ^missing(aeendtc);
create table chk_per as select distinct /*aperiod,*/ trtp,trta,extrt,subjid,visitnum,visit from toflg;
quit;

%all_dist_in_one(in=toflg,lib=work,ind=none,excl=,grp=usubjid aeterm astdt aendt trtsdt adurfdc adurldc adurn adurc);
proc sql;
create table test as select * from toflg /*where missing(aperiod)*/;
quit;
*** flags ;
%let trtfl=trtp;

**Any; 
   * any AE ; 
%flag(datain=toflg,dataout=toflg01,flag=aocc01fl,cond=%str(^missing(usubjid)),by=&trtfl usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Any AE Flag) );
   * TEAE ; 
%flag(datain=toflg01,dataout=toflg02,flag=aocc02fl,cond=%str(^missing(usubjid) and  lowcase(trtemfl)="y"),by=&trtfl usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Any TEAE Flag) );
  * related ;
%flag(datain=toflg02,dataout=toflg03,flag=aocc03fl,cond=%str(^missing(usubjid) and relflg in (3)),by=&trtfl usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Any Related Flag) );
  * severity ;
%flag(datain=toflg03,dataout=toflg04,flag=aocc04fl,cond=%str(^missing(usubjid) and ^missing(asevn)),by=&trtfl usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Any Severity Flag) );
  * serious ;
%flag(datain=toflg04,dataout=toflg05,flag=aocc05fl,cond=%str(^missing(usubjid) and upcase(aeser)="Y"),by=&trtfl usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Any Serious Flag) );

**by subject; 
   * Any AE ; 
%flag(datain=toflg05,dataout=toflg06,flag=aoccfl,cond=%str(^missing(usubjid)),by=&trtfl usubjid aestdtc aeseq,
   first=usubjid,flabel=%str(1st Occurrence within Subject Flag) );
   * TEAE ; 
%flag(datain=toflg06,dataout=toflg07,flag=aocctfl,cond=%str(^missing(usubjid) and lowcase(trtemfl) = "y"),by=&trtfl usubjid aestdtc aeseq,
   first=usubjid,flabel=%str(1st Occurrence of Any TEAE Flag) );
   * SOC ; 
%flag(datain=toflg07,dataout=toflg08,flag=aoccsfl,cond=%str(^missing(usubjid)),by=&trtfl usubjid aebodsys aestdtc aeseq,
   first=aebodsys,flabel=%str(1st Occurrence of SOC Flag) ); * Do we need trtemfl - 'Y' ?; 
   * PT ; 
%flag(datain=toflg08,dataout=toflg09,flag=aoccpfl,cond=%str(^missing(usubjid)),by=&trtfl usubjid aebodsys aedecod aestdtc aeseq,
   first=aedecod,flabel=%str(1st Occurrence of Preferred Term Flag) );* Do we need trtemfl - 'Y' ?; 

** teae related ;
%flag(datain=toflg09,dataout=toflg10,flag=aocc06fl,cond=%str(lowcase(trtemfl)="y" and relflg in (3) ),
   by=&trtfl usubjid relflg aestdtc aeseq,first=usubjid,flabel=%str(1st Occurrence Subject Related Flag) );
%flag(datain=toflg10,dataout=toflg11,flag=aocc07fl,cond=%str(lowcase(trtemfl)="y" and relflg ^in (.) ),
   by=&trtfl usubjid relflg aestdtc aeseq,first=relflg,flabel=%str(1st Occur. by Rel. Subject Related Flag) );
%flag(datain=toflg11,dataout=toflg12,flag=aocc08fl,cond=%str(lowcase(trtemfl)="y" and relflg ^in (.)),
   by=&trtfl usubjid aebodsys relflg aestdtc aeseq,first=relflg,flabel=%str(1st Occur. by Rel. Subject Rel. SOC Flag) );
%flag(datain=toflg12,dataout=toflg13,flag=aocc09fl,cond=%str(lowcase(trtemfl)="y" and relflg ^in (.)),
   by=&trtfl usubjid aebodsys aedecod relflg aestdtc aeseq,first=relflg,flabel=%str(1st Occur. by Rel. Subject Rel. PT Flag) );

** teae severity ;
  * -- for max severity, flag 1 subj/soc/pt by descending sev;
%flag(datain=toflg13,dataout=toflg14,flag=aoccifl,cond=%str(lowcase(trtemfl)="y" and ^missing(asevn)),
   by=&trtfl usubjid descending asevn aestdtc aeseq,first=usubjid,flabel=%str(1st Max Sev./Int. Occurrence Flag) );
%flag(datain=toflg14,dataout=toflg15,flag=aoccsifl,cond=%str(lowcase(trtemfl)="y" and ^missing(asevn)),
   by=&trtfl usubjid aebodsys descending asevn aestdtc aeseq,first=aebodsys,flabel=%str(1st Max Sev./Int. Occur Within SOC Flag) );
%flag(datain=toflg15,dataout=toflg16,flag=aoccpifl,cond=%str(lowcase(trtemfl)="y" and ^missing(asevn)),
   by=&trtfl usubjid aebodsys aedecod descending asevn aestdtc aeseq,first=aedecod,flabel=%str(1st Max Sev./Int. Occur Within PT Flag) );

** teae serious ;
%flag(datain=toflg16,dataout=toflg17,flag=aocc10fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aeser)="y"),
   by=&trtfl usubjid aestdtc aeseq,first=usubjid,flabel=%str(1st Occurrence Subject Serious Flag) );
%flag(datain=toflg17,dataout=toflg18,flag=aocc11fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aeser)="y" and relflg in (3) ),
   by=&trtfl usubjid relflg aestdtc aeseq,first=usubjid,flabel=%str(1st Occur. Subject Serious Related Flag) );

** discontinuation teae ;
%flag(datain=toflg18,dataout=toflg19,flag=aocc12fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aedisc)="y"),
   by=&trtfl usubjid aestdtc aeseq,first=usubjid,flabel=%str(1st Occur. Subject Discontinuation Flag) );

** death teae ;
%flag(datain=toflg19,dataout=toflg20,flag=aocc13fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aesdth)="y"),
   by=&trtfl usubjid aestdtc aeseq,
   first=usubjid,flabel=%str(1st Occurrence Subject Death Flag) );

** overall any ;
  * ae ;
%flag(datain=toflg20,dataout=toflg21,flag=aocc14fl,cond=%str(usubjid ne ""),by=usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occur. Overall Any AE Flag) );
  * teae ;
%flag(datain=toflg21,dataout=toflg22,flag=aocc15fl,cond=%str(^missing(usubjid) and lowcase(trtemfl)="y"),by=usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Overall Any TEAE Flag) );
  * related ;
%flag(datain=toflg22,dataout=toflg23,flag=aocc16fl,cond=%str(^missing(usubjid) and relflg in (3)),by=usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Overall Any Related Flag) );
  * severity ;
%flag(datain=toflg23,dataout=toflg24,flag=aocc17fl,cond=%str(^missing(usubjid) and ^missing(asevn)),by=usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Overall Any Severity Flag) );
  * sae ;
%flag(datain=toflg24,dataout=toflg25,flag=aocc18fl,cond=%str(^missing(usubjid) and upcase(aeser)='Y'),by=usubjid aestdtc aeseq,
   first=aeseq,flabel=%str(1st Occurrence Overall Any Serious Flag) );

 ** Overall by subject ;
  * ae ;
%flag(datain=toflg25,dataout=toflg26,flag=aocc19fl,cond=%str(^missing(usubjid)),by=usubjid aestdtc aeseq,
   first=usubjid,flabel=%str(1st Occurrence Overall Subject AE Flag) );
  * teae ; 
%flag(datain=toflg26,dataout=toflg27,flag=aocc20fl,cond=%str(^missing(usubjid) and lowcase(trtemfl)="y"),by=usubjid aestdtc aeseq,
   first=usubjid,flabel=%str(1st Occurrence Overall Subject TEAE Flag) );
  * Related ; 
%flag(datain=toflg27,dataout=toflg28,flag=aocc21fl,cond=%str(^missing(usubjid) and lowcase(trtemfl)="y" and relflg in (3) ),
   by=usubjid relflg aestdtc aeseq,first=usubjid,flabel=%str(1st Occur. Overall Subject Related Flag) );
  * serious teae ;
%flag(datain=toflg28,dataout=toflg29,flag=aocc22fl,cond=%str(^missing(usubjid) and lowcase(trtemfl)="y" and lowcase(aeser)="y" ),
   by=usubjid relflg aestdtc aeseq,first=usubjid,flabel=%str(1st Occur. Overall Subject Serious Flag) );
  * severity teae ; 
%flag(datain=toflg29,dataout=toflg30,flag=aocc23fl,cond=%str(lowcase(trtemfl)="y" and ^missing(asevn)),
   by=usubjid relflg aestdtc aeseq,first=usubjid,flabel=%str(1st Occur. Overall Subject Severity Flag) );
  * discontinuation teae ;
%flag(datain=toflg30,dataout=toflg31,flag=aocc24fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aedisc)="y"),
   by=usubjid aestdtc aeseq,first=usubjid,flabel=%str(1st Occur. Overall Subject Discont. Flag) );
  * death teae ;
%flag(datain=toflg31,dataout=toflg32,flag=aocc25fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aesdth)="y"),by=usubjid aestdtc aeseq,
   first=usubjid,flabel=%str(1st Occur. Overall Subject Death Flag) );

 ** by subject ;
  * related ;
%flag(datain=toflg32,dataout=toflg33,flag=aocc26fl,cond=%str(lowcase(trtemfl)="y" and relflg in (3)),
   by=&trtfl usubjid aebodsys aestdtc aeseq,first=aebodsys,flabel=%str(1st Occurrence Serious SOC Flag) );
%flag(datain=toflg33,dataout=toflg34,flag=aocc27fl,cond=%str(lowcase(trtemfl)="y" and relflg in (3)),
   by=&trtfl usubjid aebodsys aedecod aestdtc aeseq,first=aedecod,flabel=%str(1st Occurrence Serious PT Flag) );
  * serious ;
%flag(datain=toflg34,dataout=toflg35,flag=aocc28fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aeser)="y"),
   by=&trtfl usubjid aebodsys aestdtc aeseq,first=aebodsys,flabel=%str(1st Occurrence Serious SOC Flag) );
%flag(datain=toflg35,dataout=toflg36,flag=aocc29fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aeser)="y"),
   by=&trtfl usubjid aebodsys aedecod aestdtc aeseq,first=aedecod,flabel=%str(1st Occurrence Serious PT Flag) );
  * discontinuation teae ;
%flag(datain=toflg36,dataout=toflg37,flag=aocc30fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aedisc)="y"),
   by=&trtfl usubjid aebodsys aestdtc aeseq,first=aebodsys,flabel=%str(1st Occur. Discontinuation SOC Flag) );
%flag(datain=toflg37,dataout=toflg38,flag=aocc31fl,cond=%str(lowcase(trtemfl)="y" and lowcase(aedisc)="y"),
   by=&trtfl usubjid aebodsys aedecod aestdtc aeseq,first=aedecod,flabel=%str(1st Occurrence Discont. PT Flag) );
data final; set toflg38; run;
proc sql noprint;
select distinct name into :flags separated by ",r." from dictionary.columns
   where lowcase(libname)="work" and lowcase(memname)="final" and index(lowcase(name),"aocc");
quit;
%put ***(flags=&flags)***;
%sqlstar(lib=adam,not=trtp trtpn trta trtan,ds=adsl,ali=l);
proc sql;
   create table adamw.adae(label="Adverse Event Analysis Dataset" sortedby=studyid usubjid aeseq) as
   select l.studyid,l.usubjid,l.subjid,l.siteid,l.armcd,l.actarmcd, r.aeseq,l.saffl,l.pkfl,/*l.trt01pn,l.trt01p,l.trt01an,l.trt01a,*/
   aeterm,aedecod,aebodsys,aellt,aelltcd,aeptcd,aehlt,aehltcd,aehlgt %vchk(final,aehltgcd,sql=y),aesoc,aesoccd,
   aestdtc,astdt,astdtm /*%vchk(final,astdtf,sql=y) %vchk(final,asttmf,sql=y)*/,aeendtc,aendt,
   aendtm /*%vchk(final,aendtf,sql=y) %vchk(final,aentmf,sql=y)*/,astdy,aestdy,aendy,aeendy,adurn,aduru 
   %vchk(final,aedur,sql=y) %vchk(final,adurc,sql=y) %vchk(final,adurfdc,sql=y) %vchk(final,adurldc,sql=y)
   /*%vchk(final,aperiod,sql=y) %vchk(final,aperiodc,sql=y) %vchk(final,aphase,sql=y)*/,
   trtemfl,/*aetrtem,*/prefl,fupfl,r.&flags,trtp,trtpn,trta,trtan,aeser,/*aesev,aesevn,*/asev,asevn,/*aerel,aereln,*/arel,areln,aepatt,
   /*%vchk(final,aetoxgr,sql=y) %vchk(final,aetoxgrn,sql=y) %vchk(final,atoxgr,sql=y) %vchk(final,atoxgrn,sql=y),*/
   aeacn %vchk(final,aeacnoth,sql=y),aeout %vchk(final,aedisc,sql=y), aemederr,aecontrt,aesdth,r.aespid/*,timechg*/, r.cmno
   from adam.adsl as l, final as r
   where l.usubjid = r.usubjid
   order by studyid,usubjid,aeseq
   ;
quit;

%clrw;